/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package components.panels;

import components.utils.TableColumnAdjuster;
import components.utils.observer.TestsInputTableUpdater;
import control.Application;
import entity.Sample;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author Juan
 */
public class PSamplesInput extends javax.swing.JPanel {
    
    private TableColumnAdjuster samplesTCA;
    private TableColumnAdjuster testsTCA;
    private List samples;
    private TestsInputTableUpdater tableUpdater;

    /**
     * Creates new form PSamplesInput
     */
    public PSamplesInput() {
        initComponents();
        samplesTCA = new TableColumnAdjuster(TSamples);
        samplesTCA.adjustColumns();
        testsTCA = new TableColumnAdjuster(TTests);
        
        DefaultTableModel model = (DefaultTableModel) TSamples.getModel();
        model.addTableModelListener(new TableModelListener() {

            @Override
            public void tableChanged(TableModelEvent e) {
                if (e.getColumn() >= 0) {
                    samplesTCA.adjustColumn(TSamples.convertColumnIndexToModel(e.getColumn()));
                }
            }
        });
        
        TSamples.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (TSamples.getSelectedRow() != -1) {
                    BRemoveSample.setEnabled(true);
                }else{
                    BRemoveSample.setEnabled(false);
                }
            }
        });
        
        TableColumn stateColumn = TSamples.getColumn("Estado");
        JComboBox jComboBox = new JComboBox();
        jComboBox.addItem("Seleccione...");
        
        //Load the list of states from the static property of the class Sample.
        for (Object state : Sample.STATES) {
            jComboBox.addItem(state);
        }
        stateColumn.setCellEditor(new DefaultCellEditor(jComboBox));
        stateColumn.setPreferredWidth(130);
    }

    public void setTableUpdater(TestsInputTableUpdater tableUpdater) {
        this.tableUpdater = tableUpdater;
        tableUpdater.setTable(TTests);
        tableUpdater.setTca(testsTCA);
        tableUpdater.notifyObserver();
    }
    
    public boolean validFields () {
        samples = new ArrayList();
        DefaultTableModel model = (DefaultTableModel) TSamples.getModel();
        List selectedTests = TTests.getSelectedTests();
        boolean result = true;
        
        if (selectedTests.isEmpty()) {
            JOptionPane.showMessageDialog(this.getTopLevelAncestor(),
                            "No se ha seleccionado ningún análisis",
                            "Advertencia", JOptionPane.WARNING_MESSAGE);
            result = false;
        } else {
            //Samples initial validations.
            for (int i = 0; i < model.getRowCount(); i++) {
                Sample currentSample = new Sample();

                //Sample name validation.
                String name = (String) model.getValueAt(i, 0);
                if (name == null || name.length() == 0) {
                    JOptionPane.showMessageDialog(this.getTopLevelAncestor(),
                            "No se ha especificado una identificación para la muestra " + (i+1),
                            "Advertencia", JOptionPane.WARNING_MESSAGE);
                    TSamples.getSelectionModel().setSelectionInterval(i, i);
                    result = false;
                    break;
                } else {
                    currentSample.setName(name);
                }

                //Sample quantity validation.
                Float quantity = (Float) model.getValueAt(i, 1);
                if (quantity == null || quantity <= 0) {
                    JOptionPane.showMessageDialog(this.getTopLevelAncestor(),
                            "No se ha especificado una cantidad válida para la muestra " + (i+1),
                            "Advertencia", JOptionPane.WARNING_MESSAGE);
                    TSamples.getSelectionModel().setSelectionInterval(i, i);
                    result = false;
                    break;
                } else {
                    currentSample.setQuantity(quantity);
                }

                //Sample state validation.
                String state = (String) model.getValueAt(i, 4);
                if (state.equals("Seleccione...")) {
                    JOptionPane.showMessageDialog(this.getTopLevelAncestor(),
                            "No se ha seleccionado un estado para la muestra " + (i+1),
                            "Advertencia", JOptionPane.WARNING_MESSAGE);
                    TSamples.getSelectionModel().setSelectionInterval(i, i);
                    result = false;
                    break;
                } else {
                    currentSample.setState(Sample.STATES.indexOf(state));
                }

                currentSample.setRadioactive((boolean) model.getValueAt(i, 2));
                currentSample.setMagnetic((boolean) model.getValueAt(i, 3));
                currentSample.setPhotographicRecord((boolean) model.getValueAt(i, 5));
                currentSample.setComments((String) model.getValueAt(i, 6));
                currentSample.setTests(selectedTests);
                currentSample.setId(Application.sampleID++);

                samples.add(currentSample);
            }
        }
        
        
        if (!result) {
            samples.clear();
        } else if (samples.isEmpty()) {
            result = false;
            JOptionPane.showMessageDialog(this.getTopLevelAncestor(),
                            "Por favor agregue al menos una muestra.",
                            "Advertencia", JOptionPane.WARNING_MESSAGE);
        }
        
        return result;
    }
    
    public List getSamples () {
        return samples;
    }
    
    public void setSamples(List samples) {
        BAddSample.setVisible(false);
        BRemoveSample.setVisible(false);
        TSamples.setEnabled(false);
        if (samples != null && !samples.isEmpty()) {
            Sample firstSample = (Sample) samples.get(0);
            TTests.setTestsForDisplay(firstSample.getTests());
            testsTCA.adjustColumns();
            
            DefaultTableModel model = (DefaultTableModel) TSamples.getModel();
            model.setRowCount(0);
            for (Iterator it = samples.iterator(); it.hasNext();) {
                Sample sample = (Sample) it.next();
                model.addRow(new Object[]{sample.getName(),
                    sample.getQuantity(),
                    sample.getRadioactive(),
                    sample.getMagnetic(),
                    Sample.STATES.get(sample.getState()),
                    sample.getPhotographicRecord(),
                    sample.getComments()
                });
            }
            samplesTCA.adjustColumns();
        }
    }
    
    public void stopEditing() {
        if (TSamples.isEditing()) {
            TSamples.getCellEditor().stopCellEditing();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        TSamples = new javax.swing.JTable();
        BAddSample = new javax.swing.JButton();
        BRemoveSample = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        TTests = new components.TestsInputTable();

        TSamples.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"", null,  new Boolean(false),  new Boolean(false), "Seleccione...",  new Boolean(false), ""}
            },
            new String [] {
                "Identificación", "Cantidad (g)", "Radioactiva", "Magnética", "Estado", "Registro Fotográfico", "Observaciones"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Float.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Object.class, java.lang.Boolean.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        TSamples.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        TSamples.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        TSamples.setEditingColumn(0);
        TSamples.setEditingRow(0);
        TSamples.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        TSamples.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(TSamples);

        BAddSample.setText("Agregar Muestra");
        BAddSample.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BAddSampleActionPerformed(evt);
            }
        });

        BRemoveSample.setText("EliminarMuestra");
        BRemoveSample.setEnabled(false);
        BRemoveSample.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BRemoveSampleActionPerformed(evt);
            }
        });

        jLabel1.setText("Muestras:");

        jLabel2.setText("Análisis:");

        TTests.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Normal", "Rush", "Nombre"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.Boolean.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        TTests.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jScrollPane4.setViewportView(TTests);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(BAddSample)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(BRemoveSample))
                    .addComponent(jLabel1)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 609, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addContainerGap(169, Short.MAX_VALUE))
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(BRemoveSample)
                    .addComponent(BAddSample)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void BRemoveSampleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BRemoveSampleActionPerformed
        DefaultTableModel model = (DefaultTableModel) TSamples.getModel();
        int selectedRow = TSamples.getSelectedRow();
        model.removeRow(selectedRow);
        
        if (selectedRow == 0)
            if (TSamples.getRowCount() == 0)
                TSamples.getSelectionModel().setSelectionInterval(-1, -1);
            else
                TSamples.getSelectionModel().setSelectionInterval(0, 0);
        else
            TSamples.getSelectionModel().setSelectionInterval(selectedRow - 1, selectedRow - 1);
    }//GEN-LAST:event_BRemoveSampleActionPerformed

    private void BAddSampleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BAddSampleActionPerformed
        DefaultTableModel model = (DefaultTableModel) TSamples.getModel();
        model.addRow(new Object[] {"",null,false,false,"Seleccione...",false,""});
        TSamples.changeSelection(TSamples.getRowCount() - 1, 0, false, false);
    }//GEN-LAST:event_BAddSampleActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BAddSample;
    private javax.swing.JButton BRemoveSample;
    private javax.swing.JTable TSamples;
    private components.TestsInputTable TTests;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane4;
    // End of variables declaration//GEN-END:variables
}
